const mysql = require('mysql')

var pool = mysql.createPool({
  host     : 'localhost',
  user     : 'root',
  password : 'secret',
  database : 'crm'
});

let query = function( sql, values ) {
  return new Promise(( resolve, reject ) => {
    pool.getConnection(function(err, connection) {
      if (err) {
        reject( err )
      } else {
        connection.query(sql, values, ( err, rows) => {
          if ( err ) {
            reject( err )
          } else {
            resolve( rows )
          }
          connection.release()
        })
      }
    })
  })
}

// 注册用户
let insertData = function( value ) {
  let _sql = "insert into users set name=?,age=?;"
  return query( _sql, [value.name, value.age] )
}

// 查询用户
let selectData = function() {
  let _sql = "select * from users;"
  return query( _sql )
}

module.exports = { insertData, selectData }
